package com.apes.scm.masterdata.party.repository;


import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.scm.masterdata.party.model.Party;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author xul
 * @create 2018-01-23 16:07
 */
public interface PartyRepository extends CustomRepository<Party, Long> {

    @Query("SELECT T FROM Party T WHERE 1 = 1 and (id = :id or name like %:value%) ") //or name like %:value%
    Page<Party> find( @Param("id") long id, @Param("value") String value, Pageable pageable);

    @Query("SELECT T FROM Party T WHERE 1 = 1 and partyType = :type  and (id = :id or name like %:value%) ") 
    Page<Party> findPerson(@Param("type") String type, @Param("id") long id, @Param("value") String value, Pageable pageable);

    @Query(" SELECT T FROM Party T JOIN T.partyRoles B WHERE B.role.id = 'Company' AND (T.id like :id OR T.name LIKE %:name%)")
    Page<Party> findCompany(@Param("id")long id, @Param("name")String name, Pageable pageable);

    List<Party> findByOrigin(String originId);

    @Query("select t from Party t join t.partyRoles b where b.role.id = :roleType and t.name = :name ")
    List<Party> findByRoleIdAnAndName(@Param("roleType") String roleType, @Param("name") String name);

    @Query(value = "" +
            "SELECT A.ID, " +
            "       NVL((SELECT ID FROM MAS_PARTY_ROLE C " +
            "          WHERE C.PARTY_ID = A.ID AND C.ROLE_ID = 'Operator'), A.BELONG_OPERATOR) OPERATOR_ID " +
            "  FROM MAS_PARTY A, MAS_PARTY_ROLE B " +
            " WHERE A.ID = B.PARTY_ID " +
            "   AND B.ID = ?1 ", nativeQuery = true)
    List<Map> findOperator(String companyId);
}
